package controller

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/kataras/iris/mvc"
	"imooc.com/demo_pms/web/utils"
)

func (a *UserInfoController) GetBatchupload() mvc.Result {
	return mvc.View{
		Name: "upload.html",
		Data: map[string]string{
			"usermsg": "",
			"paymsg":  "",
		},
	}
}

func (a *UserInfoController) PostBatchupload() mvc.Result {
	file, _, err := a.Ctx.FormFile("uploadfile")
	if err != nil {
		return mvc.View{
			Name: "upload.html",
			Data: map[string]string{
				"usermsg": "上传的文件错误",
				"paymsg":  "",
			},
		}
	}
	defer file.Close()

	out, err := excelize.OpenReader(file)
	if err != nil {
		return mvc.View{
			Name: "upload.html",
			Data: map[string]string{
				"usermsg": "excel包读取错误",
				"paymsg":  "",
			},
		}
	}
	// 获取Sheet1表格数据
	rows := out.GetRows("Sheet1")
	// excel 数据转化为 用户信息，工资信息
	userList, payList := utils.ExcelToDbInfo(rows)
	// 到上面的用户信息转换没问题，下面插入会显示为空地址，应该是某个变量没初始化
	// 找找看，找到原因了，再router里面要初始化service并注册进去
	i1, err1 := a.UserService.BatchCreate(userList)
	i2, err2 := a.PayService.Create(payList)
	return mvc.View{
		Name: "upload.html",
		Data: map[string]string{
			"usermsg": fmt.Sprintf("成功导入用户%d，"+
				"error=%s", i1, err1),
			"paymsg": fmt.Sprintf("成功导入工资信息%d，"+
				"error=%s", i2, err2),
		},
	}
}

//func (a *UserInfoController) GetDownload()mvc.Result{
//
//}
